package com.zkyt.lib_msdk_ext.utils

import android.view.View
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.Optional
import java.util.concurrent.TimeUnit

/**
 * Created by chenyu on 2024/2/18
 * Description:
 */


object RxExt {

    fun <T> Observable<Optional<T>>.filterGetOptional(): Observable<T> {
        return this.compose { upstream ->
            upstream.filter { it.isPresent }
                .map { it.get() }
        }
    }

    fun <T> Observable<T>.toUI(): Observable<T> {
        return this.compose(RxExt.toUI())
    }

    fun Completable.toUI(): Completable {
        return this.compose{ upstream ->
            upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

    private fun <T> toUI(): ObservableTransformer<T, T> {
        return ObservableTransformer { upstream ->
            upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

    fun <T> Observable<T>.distinctToUI(): Observable<T> {
        return this.compose(RxExt.distinctToUI())
    }

    private fun <T> distinctToUI(): ObservableTransformer<T, T> {
        return ObservableTransformer { upstream ->
            upstream.distinctUntilChanged()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

    fun <T> Observable<T>.throttleDistinctToUI(interval: Long = 200): Observable<T> {
        return this.compose(RxExt.throttleDistinctToUI(interval))
    }

    private fun <T> throttleDistinctToUI(interval: Long = 200): ObservableTransformer<T, T> {
        return ObservableTransformer { upstream ->
            upstream.throttleLatest(interval, java.util.concurrent.TimeUnit.MILLISECONDS)
                .distinctUntilChanged()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

    fun <T> Observable<T>.throttleToUI(interval: Long = 200): Observable<T> {
        return this.compose(RxExt.throttleToUI(interval))
    }

    private fun <T> throttleToUI(interval: Long = 200): ObservableTransformer<T, T> {
        return ObservableTransformer { upstream ->
            upstream.throttleLatest(interval, java.util.concurrent.TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

    /**
     * view的滤波click，防止短时间内多次点击
     * 时间窗口：200ms
     *
     * @return
     */
//    fun View.throttleClick(interval: Long = 500): Observable<Any> {
//        return RxView.clicks(this)
//            .throttleFirst(interval, TimeUnit.MILLISECONDS)
//            .observeOn(AndroidSchedulers.mainThread())
//    }

}